from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.filters import SearchFilter, OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend
from django.contrib.auth.models import Permission as DjangoPermission, Group as DjangoGroup
from django.contrib.auth import get_user_model
from django.db.models import Q
from drf_spectacular.utils import extend_schema_view, extend_schema, OpenApiParameter
from drf_spectacular.types import OpenApiTypes

from apps.common.responses import (
    ApiResponseMixin,
    ConfigurableActionMixin,
    create_success_response_serializer,
    NotFoundErrorResponseSerializer,
    ValidationErrorResponseSerializer
)
from .models import PermissionCategory, PermissionExtension, RoleExtension, UserRoleAssignment
from .serializers import (
    PermissionCategorySerializer,
    PermissionExtensionSerializer,
    PermissionDetailSerializer,
    RoleExtensionSerializer,
    RoleDetailSerializer,
    UserRoleAssignmentSerializer
)

User = get_user_model()


@extend_schema_view(
    list=extend_schema(
        summary="获取权限分类列表",
        description="获取所有权限分类，支持分页、搜索、排序",
        parameters=[
            OpenApiParameter(name='name', type=OpenApiTypes.STR, description='分类名称搜索'),
        ],
    ),
    retrieve=extend_schema(
        summary="获取权限分类详情",
        responses={
            200: create_success_response_serializer(PermissionCategorySerializer, "获取成功", "Retrieve"),
            404: NotFoundErrorResponseSerializer,
        }
    ),
    create=extend_schema(
        summary="创建权限分类",
        responses={
            201: create_success_response_serializer(PermissionCategorySerializer, "创建成功", "Create"),
            400: ValidationErrorResponseSerializer,
        }
    ),
    update=extend_schema(
        summary="更新权限分类",
        responses={
            200: create_success_response_serializer(PermissionCategorySerializer, "更新成功", "Update"),
            400: ValidationErrorResponseSerializer,
            404: NotFoundErrorResponseSerializer,
        }
    ),
    destroy=extend_schema(
        summary="删除权限分类",
        responses={
            204: None,
            404: NotFoundErrorResponseSerializer,
        }
    ),
)
class PermissionCategoryViewSet(ConfigurableActionMixin, ApiResponseMixin, viewsets.ModelViewSet):
    """权限分类管理"""

    queryset = PermissionCategory.objects.all()
    serializer_class = PermissionCategorySerializer
#    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    search_fields = ['name', 'code', 'description']
    filterset_fields = ['code']
    ordering_fields = ['sort_order', 'name', 'created_at']
    ordering = ['sort_order', 'name']


@extend_schema_view(
    list=extend_schema(
        summary="获取权限列表",
        description="获取所有权限信息，支持分页、搜索、过滤、排序",
        parameters=[
            OpenApiParameter(name='module', type=OpenApiTypes.STR, description='模块过滤'),
            OpenApiParameter(name='status', type=OpenApiTypes.STR, description='状态过滤'),
        ],
    ),
    retrieve=extend_schema(
        summary="获取权限详情",
        responses={
            200: create_success_response_serializer(PermissionDetailSerializer, "获取成功", "Retrieve"),
            404: NotFoundErrorResponseSerializer,
        }
    ),
    create=extend_schema(
        summary="创建权限",
        responses={
            201: create_success_response_serializer(PermissionExtensionSerializer, "创建成功", "Create"),
            400: ValidationErrorResponseSerializer,
        }
    ),
    update=extend_schema(
        summary="更新权限",
        responses={
            200: create_success_response_serializer(PermissionExtensionSerializer, "更新成功", "Update"),
            400: ValidationErrorResponseSerializer,
            404: NotFoundErrorResponseSerializer,
        }
    ),
    destroy=extend_schema(
        summary="删除权限",
        responses={
            204: None,
            404: NotFoundErrorResponseSerializer,
        }
    ),
)
class PermissionViewSet(ConfigurableActionMixin, ApiResponseMixin, viewsets.ModelViewSet):
    """权限管理"""

    queryset = PermissionExtension.objects.select_related(
        'permission', 'category'
    ).filter(status='active')
    serializer_class = PermissionExtensionSerializer
#    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    search_fields = ['permission__name', 'permission__codename', 'module', 'description']
    filterset_fields = ['module', 'status', 'category']
    ordering_fields = ['sort_order', 'module', 'permission__name', 'created_at']
    ordering = ['sort_order', 'module', 'permission__name']

    def get_serializer_class(self):
        if self.action == 'retrieve':
            return PermissionDetailSerializer
        return super().get_serializer_class()

    # 配置：禁用分页
    action_configs = {
        'by_module': {
            'use_pagination': False,
            'search_fields': ['permission__name', 'module'],
            'filterset_fields': ['module', 'status'],
            'ordering_fields': ['sort_order', 'module'],
        }
    }

    @extend_schema(
        summary="按模块获取权限",
        description="按模块分组获取权限列表",
        request=None,
        responses={
            200: create_success_response_serializer(PermissionExtensionSerializer(many=True), "获取成功", "PermissionsByModule"),
        }
    )
    @action(detail=False, methods=['get'])
    def by_module(self, request):
        """按模块获取权限"""
        queryset = self.get_queryset()
        queryset = self.apply_action_filters(queryset, request, self.get_action_config('by_module'))

        modules = {}
        for perm in queryset:
            module = perm.module
            if module not in modules:
                modules[module] = []
            modules[module].append(self.get_serializer(perm).data)

        return self.success_response(modules, "获取成功")


@extend_schema_view(
    list=extend_schema(
        summary="获取角色列表",
        description="获取所有角色信息，支持分页、搜索、过滤、排序",
        parameters=[
            OpenApiParameter(name='status', type=OpenApiTypes.STR, description='状态过滤'),
            OpenApiParameter(name='is_system', type=OpenApiTypes.BOOL, description='是否系统角色'),
        ],
    ),
    retrieve=extend_schema(
        summary="获取角色详情",
        responses={
            200: create_success_response_serializer(RoleDetailSerializer, "获取成功", "Retrieve"),
            404: NotFoundErrorResponseSerializer,
        }
    ),
    create=extend_schema(
        summary="创建角色",
        responses={
            201: create_success_response_serializer(RoleExtensionSerializer, "创建成功", "Create"),
            400: ValidationErrorResponseSerializer,
        }
    ),
    update=extend_schema(
        summary="更新角色",
        responses={
            200: create_success_response_serializer(RoleExtensionSerializer, "更新成功", "Update"),
            400: ValidationErrorResponseSerializer,
            404: NotFoundErrorResponseSerializer,
        }
    ),
    destroy=extend_schema(
        summary="删除角色",
        responses={
            204: None,
            404: NotFoundErrorResponseSerializer,
        }
    ),
)
class RoleViewSet(ConfigurableActionMixin, ApiResponseMixin, viewsets.ModelViewSet):
    """角色管理"""

    queryset = RoleExtension.objects.select_related('group').filter(status='active')
    serializer_class = RoleExtensionSerializer
#    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    search_fields = ['group__name', 'code', 'description']
    filterset_fields = ['status', 'is_system', 'level']
    ordering_fields = ['sort_order', 'level', 'group__name', 'created_at']
    ordering = ['sort_order', 'level', 'group__name']

    def get_serializer_class(self):
        if self.action == 'retrieve':
            return RoleDetailSerializer
        return super().get_serializer_class()

    # 配置：禁用分页
    action_configs = {
        'permissions': {
            'use_pagination': False,
            'search_fields': ['permission__name', 'permission__codename'],
            'filterset_fields': ['module', 'status'],
            'ordering_fields': ['sort_order', 'module'],
        }
    }

    @extend_schema(
        summary="分配权限给角色",
        description="为指定角色分配权限",
        responses={
            200: create_success_response_serializer(None, "分配成功", "AssignPermissions"),
            400: ValidationErrorResponseSerializer,
            404: NotFoundErrorResponseSerializer,
        }
    )
    @action(detail=True, methods=['post'])
    def assign_permissions(self, request, pk=None):
        """分配权限给角色"""
        role = self.get_object()
        permission_ids = request.data.get('permission_ids', [])

        if not permission_ids:
            return self.error_response("请提供权限ID列表", code=400)

        try:
            permissions = DjangoPermission.objects.filter(id__in=permission_ids)
            if len(permissions) != len(permission_ids):
                return self.error_response("部分权限ID无效", code=400)

            role.group.permissions.set(permissions)

            return self.success_response({
                'role_id': role.id,
                'role_name': role.name,
                'permissions_count': len(permissions),
                'message': f'成功为角色 {role.name} 分配了 {len(permissions)} 个权限'
            }, "分配成功")
        except Exception as e:
            return self.error_response(f"分配权限失败: {str(e)}", code=500)

    @extend_schema(
        summary="获取角色权限",
        description="获取指定角色的所有权限",
        parameters=[
            OpenApiParameter(name='search', type=OpenApiTypes.STR, description='搜索权限名称或代码'),
            OpenApiParameter(name='module', type=OpenApiTypes.STR, description='模块过滤'),
            OpenApiParameter(name='status', type=OpenApiTypes.STR, description='状态过滤', enum=['active', 'inactive']),
            OpenApiParameter(name='ordering', type=OpenApiTypes.STR, description='排序字段', enum=['sort_order', '-sort_order', 'module', '-module']),
        ],
        request=None,
        responses={
            200: create_success_response_serializer(PermissionExtensionSerializer(many=True), "获取成功", "RolePermissions"),
            404: NotFoundErrorResponseSerializer,
        }
    )
    @action(detail=True, methods=['get'])
    def permissions(self, request, pk=None):
        """获取角色权限"""
        role = self.get_object()

        # 获取角色的所有权限扩展记录作为查询集
        queryset = PermissionExtension.objects.filter(
            permission__in=role.group.permissions.all()
        ).select_related('permission', 'category')

        # 应用配置式过滤器
        queryset = self.apply_action_filters(queryset, request, self.get_action_config('permissions'))

        # 🔑 关键：强制不分页，直接返回
        serializer = PermissionExtensionSerializer(queryset, many=True)
        return self.success_response(serializer.data, "获取角色权限列表成功")


@extend_schema_view(
    list=extend_schema(
        summary="获取用户角色分配列表",
        description="获取所有用户角色分配记录，支持分页、搜索、过滤、排序",
        parameters=[
            OpenApiParameter(name='user_id', type=OpenApiTypes.INT, description='用户ID过滤'),
            OpenApiParameter(name='role_id', type=OpenApiTypes.INT, description='角色ID过滤'),
            OpenApiParameter(name='status', type=OpenApiTypes.STR, description='状态过滤'),
        ],
    ),
    retrieve=extend_schema(
        summary="获取用户角色分配详情",
        responses={
            200: create_success_response_serializer(UserRoleAssignmentSerializer, "获取成功", "Retrieve"),
            404: NotFoundErrorResponseSerializer,
        }
    ),
    create=extend_schema(
        summary="创建用户角色分配",
        responses={
            201: create_success_response_serializer(UserRoleAssignmentSerializer, "创建成功", "Create"),
            400: ValidationErrorResponseSerializer,
        }
    ),
    update=extend_schema(
        summary="更新用户角色分配",
        responses={
            200: create_success_response_serializer(UserRoleAssignmentSerializer, "更新成功", "Update"),
            400: ValidationErrorResponseSerializer,
            404: NotFoundErrorResponseSerializer,
        }
    ),
    destroy=extend_schema(
        summary="删除用户角色分配",
        responses={
            204: None,
            404: NotFoundErrorResponseSerializer,
        }
    ),
)
class UserRoleViewSet(ConfigurableActionMixin, ApiResponseMixin, viewsets.ModelViewSet):
    """用户角色分配管理"""

    queryset = UserRoleAssignment.objects.select_related(
        'user', 'role', 'assigned_by'
    ).all()
    serializer_class = UserRoleAssignmentSerializer
#    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    search_fields = ['user__username', 'user__email', 'role__group__name', 'reason']
    filterset_fields = ['user', 'role', 'status', 'assigned_by']
    ordering_fields = ['assigned_at', 'expires_at', 'created_at']
    ordering = ['-assigned_at']

    # 配置：禁用分页
    action_configs = {
        'permissions': {
            'use_pagination': False,  # 🔑 关键：属于模式3
            'search_fields': ['user__username', 'user__email', 'role__group__name'],
            'filterset_fields': ['status', 'role'],
            'ordering_fields': ['assigned_at', 'expires_at'],
        }
    }

    @extend_schema(
        summary="分配角色给用户",
        description="为指定用户分配角色",
        request=UserRoleAssignmentSerializer,
        responses={
            200: create_success_response_serializer(UserRoleAssignmentSerializer, "分配成功", "AssignRole"),
            400: ValidationErrorResponseSerializer,
        }
    )
    @action(detail=False, methods=['post'])
    def assign_role(self, request):
        """分配角色给用户"""
        # 使用序列化器验证数据
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 获取验证后的数据
        validated_data = serializer.validated_data
        user = validated_data['user']
        role = validated_data['role']
        expires_at = validated_data.get('expires_at')
        reason = validated_data.get('reason', '')

        try:
            # 检查是否已经分配过
            assignment, created = UserRoleAssignment.objects.get_or_create(
                user=user,
                role=role,
                defaults={
                    'assigned_by': request.user,
                    'expires_at': expires_at,
                    'reason': reason,
                    'status': 'active'
                }
            )

            if not created:
                assignment.status = 'active'
                assignment.assigned_by = request.user
                assignment.expires_at = expires_at
                assignment.reason = reason
                assignment.save()

            # 同时添加到Django的用户组中
            user.groups.add(role.group)

            # 返回创建/更新后的数据
            result_serializer = self.get_serializer(assignment)
            return self.success_response(
                result_serializer.data,
                f"成功为用户 {user.username} 分配角色 {role.group.name}"
            )

        except Exception as e:
            return self.error_response(f"分配角色失败: {str(e)}", code=500)

    # Schema：手动指定响应格式
    @extend_schema(
        summary="获取用户权限",
        description="获取指定用户的所有权限和角色",
        parameters=[
            OpenApiParameter(name='search', type=OpenApiTypes.STR, description='搜索用户名、邮箱或角色名'),
            OpenApiParameter(name='status', type=OpenApiTypes.STR, description='状态过滤', enum=['active', 'inactive', 'expired']),
            OpenApiParameter(name='role', type=OpenApiTypes.INT, description='角色ID过滤'),
            OpenApiParameter(name='ordering', type=OpenApiTypes.STR, description='排序字段', enum=['assigned_at', '-assigned_at', 'expires_at', '-expires_at']),
        ],
        responses={200: create_success_response_serializer(UserRoleAssignmentSerializer(many=True), "获取用户权限成功", "UserPermissions")},
        request=None  # 🔑 关键：明确指定不需要请求体
    )
    @action(detail=True, methods=['get'])
    def permissions(self, request, pk=None):
        """获取用户权限"""
        user_role_assignment = self.get_object()

        # 获取该用户的所有角色分配记录作为查询集
        queryset = UserRoleAssignment.objects.filter(user=user_role_assignment.user).select_related('user', 'role')

        # 应用配置式过滤器
        queryset = self.apply_action_filters(queryset, request, self.get_action_config('permissions'))

        # 🔑 关键：强制不分页，直接返回
        serializer = UserRoleAssignmentSerializer(queryset, many=True)
        return self.success_response(serializer.data, "获取用户权限成功")
